package com.xckj.cycling.activity

import com.xckj.cycling.framework.BaseActivity
import com.xckj.cycling.R
import com.xckj.cycling.utils.SpUtil
import android.content.Intent
import android.os.Handler
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import com.gyf.immersionbar.ImmersionBar
import com.gyf.immersionbar.BarHide
import com.xckj.cycling.databinding.ActivitySplashBinding
import com.xckj.cycling.global.Constant
import com.xckj.cycling.utils.AppManager

/**
 * @Author: ChenYao
 * @Describe: 启动页
 * @Date: 2023/3/14 20:29
 */
class SplashActivity : BaseActivity<ActivitySplashBinding?>() {
    override fun loadLayout(): Int {
        return R.layout.activity_splash
    }

    override fun initData() {
        super.initData()
        if (!isTaskRoot) {
            directToMain()
            finish()
            return
        }
        val handler = Handler()
        val time = 2000
        handler.postDelayed({
            if (TextUtils.isEmpty(SpUtil.getString(this@SplashActivity, Constant.TOKEN))) {
                loginViewModel.logout()
                startActivity(Intent(this@SplashActivity, LoginActivity::class.java))
            } else {
                startActivity(Intent(this@SplashActivity, MainActivity::class.java))
            }
            finish()
        }, time.toLong())
    }


    private fun directToMain() {
        val hasToken = !TextUtils.isEmpty(SpUtil.getString(this@SplashActivity, Constant.TOKEN))

        val cls = if (hasToken) {
            MainActivity::class.java
        } else if (AppManager.getInstance().containActivity(RegisterActivity::class.java)) {
            RegisterActivity::class.java
        } else if (AppManager.getInstance().containActivity(PerfectRegisterActivity::class.java)) {
            PerfectRegisterActivity::class.java
        } else {
            LoginActivity::class.java
        }
        val main = AppManager.getInstance().getActivity(cls)
        if (main == null || main.isDestroyed) {
            startActivity(Intent(this, cls))
        }
    }

    override fun onClick(view: View) {}
    override fun createStatusBarConfig(): ImmersionBar {
        return super.createStatusBarConfig().hideBar(BarHide.FLAG_HIDE_BAR)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK) {
            true
        } else super.onKeyDown(keyCode, event)
    }
}